package com.iss.apartmentmanage.config.security;

import com.iss.apartmentmanage.model.MyResponseData;
import com.iss.apartmentmanage.service.impl.MyUserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private MyUserDetailService myUserDetailService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String userName = (String) authentication.getPrincipal(); // 这个获取表单输入中返回的用户名;
        String password = (String) authentication.getCredentials(); // 这个是表单中输入的密码；
        MyResponseData myResponseData = new MyResponseData();


        String encodePwd =passwordEncoder.encode(password);
        UserDetails userInfo=myUserDetailService.loadUserByUsername(userName);
        try {
            Boolean flag = passwordEncoder.matches(userInfo.getPassword(), encodePwd);
            if (!flag) {
                myResponseData.setErrorCode(0);
                myResponseData.setStatus("UserOrPwdError!!");
            } else {
                myResponseData.setErrorCode(1);
                myResponseData.setStatus("loginSuccess!!");
                myResponseData.setObject(userInfo);
            }
        }catch(Exception e){
            myResponseData.setErrorCode(0);
            myResponseData.setStatus("loginError!!");
            e.printStackTrace();

        }

        return new UsernamePasswordAuthenticationToken(userName, password, userInfo.getAuthorities());

    }

    @Override
    public boolean supports(Class<?> authentication) {

        //return authentication.equals(UsernamePasswordAuthenticationToken.class);
        return false;//true 开启Provider false 关闭Provider
    }
}
